﻿package com.hodgedev.net.drupal 
{
	import flash.errors.IllegalOperationError;
	import flash.events.Event;
	import flash.net.NetConnection;
	import flash.net.Responder;
	/**
	 * ...
	 * @author Brian Hodge (brian@hodgedev.com)
	 */
	public class Node extends Service
	{
		public static const NODE_GET	:String = "node.get";
		public static const NODE_SET	:String = "node.set";
		public static const NODE_DELETE	:String = "node.delete";
		
		private var _nodeResponder:Responder;
		private var _data:Object;
		private var _nodeId:int;
		
		public function Node(pServices:Services):void
		{
			if (pServices == null) throw new IllegalOperationError("A valid session id must be passed.  Make sure you are connected and pass the key.");
			_services = pServices;
			
			_nodeResponder = new Responder(_onNodeSuccess, _onNodeError);
		}
		private function _onNodeSuccess(pObject:Object):void
		{
			_data = pObject;
			dispatchEvent(new NodeEvent(NodeEvent.NODE_READY, _data));
			closeConnection();
		}
		private function _onNodeError(pObject:Object):void
		{
			for each (var item:* in pObject)
			{
				trace(item, pObject[item]);
			}
			closeConnection();
		}
		public function getData(pNodeId:int):void
		{
			_nodeId = pNodeId;
			if(_checkServiceConnected()) _nc.call(Node.NODE_GET, _nodeResponder, _sessid, pNodeId);
		}
		public override function onConnect(e:ServicesEvent):void
		{
			_services.removeEventListener(ServicesEvent.SYSTEM_CONNECTED, onConnect);
			_nc = _services.netConnection;
			_sessid = _services.sessid;
			
			getData(_nodeId);
		}
		public function get data():Object
		{
			return _data;
		}
	}
}